const {app,BrowserWindow,Menu,dialog} = require('electron')
const {fill} = require("./fill")
const {xpathListen} = require("./strScript");
const {addInput,addClick,handleMap, addQuery,} = require("./operateBind");
const {connect} = require("./websocket");
const {store} = require("./store");
const {getData, saveRes} = require("./excel");
const {myEvent} = require("./myevent");


const createWindow = (url)=>{
    const win = new BrowserWindow({
        // parent
        width: 1000,
        height: 800,
        webPreferences: {
            webviewTag: true
        }
    })


    win.on('ready-to-show',()=>{
        win.show()
    })

    const menuTemplate = [
        // 一级菜单
        {
            label: "录制动作",
            submenu: [
                {
                    label: "输入",
                    click: ()=>{
                        addInput(win)
                    },
                    accelerator: "F1"
                },
                {
                    label: "点击",
                    click: ()=>{
                        addClick(win)
                    },
                    accelerator: "F2"
                },
                {
                    label: "查询",
                    click: ()=>{
                        addQuery(win)
                    },
                    accelerator: "F3"
                },
                {
                    label: "结束录制",
                    click: ()=>{
                        //序列化map并存储
                        store.set('handleMap',JSON.stringify(Array.from(handleMap.entries())))
                    },
                    accelerator: "F4"
                },
                {
                    label: "重新录制",
                    click: ()=>{
                        handleMap.clear()
                    }
                }
            ]
        },
        {
            label: "运行",
            click: ()=>{
                    dialog.showMessageBox({
                        type: 'info',
                        title: '选择数据源',
                        message: '选择数据源',
                        buttons: ['来自小程序','来自excel','取消']
                    }).then((it)=>{
                        if (it.response === 2){
                            return
                        }
                        const map = new Map(JSON.parse(store.get('handleMap')))
                        if (map.size === 0){
                            dialog.showErrorBox("错误","脚本为空")
                            return
                        }
                        if (it.response === 0){
                            const ws = connect();
                            ws.onmessage = (e)=>{
                                fill(win,map,JSON.parse(e.data))
                            }
                            //从微信小程序中获取数据(webSocket)
                        }else if(it.response === 1){
                            //从excel中获取,弹出选择文件框
                            dialog.showOpenDialog({
                                title: "请选择excel数据源",
                                buttonLabel: "确认",
                                filters: [{
                                    name: 'excel'
                                    ,extensions: ['xls','xlsx']
                                }]
                            }).then(res =>{
                                if(!res.canceled){
                                    //未点取消
                                    const data = getData(res.filePaths[0])
                                    const entries = data.entries();
                                    let value = entries.next().value[1];
                                    let excelRes = []
                                myEvent.addListener('taskFinish',(queryRes)=>{

                                    queryRes.forEach((v,i) =>{
                                        value[`res${i}`] = v
                                    })
                                    excelRes.push(value)
                                    win.loadURL("https://vslc.ncb.edu.cn/gateway/queryGradeEntry")
                                        .then(()=> {
                                            const next = entries.next();
                                            if (next.done){
                                                // 存入excel
                                                dialog.showSaveDialog({
                                                    title: '保存结果',
                                                    buttonLabel: '保存',
                                                    filters: [
                                                        {name: 'Custom File Type',extensions: ['xlsx']}
                                                    ]
                                                }).then(res =>{
                                                    if(!res.canceled){
                                                        saveRes(excelRes,res.filePath)
                                                    }
                                                })
                                                return
                                            }
                                            value = next.value[1]
                                            fill(win,map,value)
                                        })
                                })
                                fill(win,map,value)

                                }

                            }).catch(err =>{
                                console.log(err)
                                dialog.showErrorBox("异常","未知异常")
                            })
                        }
                    })

            }
        },
        {
            label: "回到首页",
            click: ()=>{
                win.loadURL(url)
            }
        }
    ];

    let menuBuilder = Menu.buildFromTemplate(menuTemplate);

    // 加载完在加菜单,防止元素找不到
    win.webContents.addListener('did-stop-loading',()=>{
        // 加入监听事件
        win.webContents.executeJavaScript(xpathListen)
        win.setMenu(menuBuilder)
    })

    win.webContents.addListener('did-start-navigation',()=>{
        // 页面跳转前取出curr
        win.webContents.executeJavaScript(`
            localStorage.getItem('curr')
        `).then((curr)=>{
            // 存入electron-store,防止页面跳转变量消失
            store.set('curr',curr)
        })
    })
    win.loadURL(url)

    win.webContents.openDevTools()

}



app.whenReady().then(()=>{
    const url = "https://vslc.ncb.edu.cn/gateway/queryGradeEntry"
    // const url = "http://www.cnsoftbei.com/"

    createWindow(url)
    app.on('activate',()=>{
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })

})

